package com.example.order.listener;

import com.example.order.constant.MQConstants;
import com.example.order.domain.vo.OrderSkuVO;
import com.example.order.domain.vo.OrderVO;
import com.example.order.service.OrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@RequiredArgsConstructor
public class OrderDelayListener {
    private final OrderService orderService;
    private final RedisTemplate<String, Object> redisTemplate;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MQConstants.DELAY_ORDER_QUEUE_NAME),
            exchange = @Exchange(value = MQConstants.DELAY_EXCHANGE_NAME, delayed = "true"),
            key = MQConstants.DELAY_ORDER_KEY
    ))
    public void listenOrderDelayMessage(Message message) {
        // 提取订单ID
        Long orderId = Long.valueOf(new String(message.getBody()));

        // 获取消息ID，用于幂等性处理
        String messageId = message.getMessageProperties().getMessageId();

        // 使用Redis解决消息幂等性问题
        String redisKey = MQConstants.DELAY_ORDER_KEY + ":" + messageId;

        // 检查消息是否已处理过
        if (messageId != null && Boolean.TRUE.equals(redisTemplate.hasKey(redisKey))) {
            // 消息已处理过，直接返回避免重复处理
            System.out.println("消息已处理，跳过执行: " + messageId);
            return;
        }

        System.out.println("订单延迟消息：" + orderId);

        // 1. 查询订单
        OrderVO orderVO = orderService.getOrderDetail(orderId);
        // 2. 检测订单状态，判断是否已支付
        if (orderVO == null || orderVO.getStatus() != 1) {
            // 订单已支付或者订单不存在，记录已处理的消息
            if (messageId != null) {
                // 设置较短的过期时间，避免Redis中积累过多数据
                redisTemplate.opsForValue().set(redisKey, "processed", 24, java.util.concurrent.TimeUnit.HOURS);
            }
            return;
        }

        // 未支付，取消订单，恢复库存
        orderService.cancelOrder(orderId);
        System.out.println("未支付，取消订单，恢复库存");

        // 记录已处理的消息
        if (messageId != null) {
            // 设置过期时间，避免Redis中积累过多数据
            redisTemplate.opsForValue().set(redisKey, "processed", 24, java.util.concurrent.TimeUnit.HOURS);
        }
    }
}
